import { JSEncrypt } from 'jsencrypt'
import dayjs from 'dayjs'
var weekday = require('dayjs/plugin/weekday')
dayjs.extend(weekday)

/**
 *
 * @param {String} tel
 * @returns {boolean}
 */
export function isPhoneNumber(tel) {
  // const reg = /^1((3\d)|(4[57])|(5[012356789])|(7[0135678])|(8[0123456789])|(99))\d{8}$/
  const reg = /^\d{11}$/
  return reg.test(tel)
}

/**
 *
 * @param {String} username
 * @returns {boolean}
 */
export function isUsername(username) {
  const reg = /^([a-zA-Z_\u4e00-\u9fa5][a-zA-Z0-9_\u4e00-\u9fa5]{0,16})$$/
  return reg.test(username)
}

/**
 *
 * @param {String} str
 * @returns {boolean}
 */
export function isEmpty(str) {
  return str === null || str === undefined || str === ''
}

/**
 *
 * @param {Number} length
 * @returns {string}
 */
export function randomString(length) {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyz'
  let result = ''
  for (let i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)]
  return result
}

/**
 *
 * @param {String} str
 * @returns {*|parser.Node[]|string}
 */
export function getSuffix(str) {
  const arr = str.split('.')
  if (arr.length > 1) {
    return arr[arr.length - 1]
  }
  return ''
}

/**
 * 判断密码登录方式
 * @param username
 * @returns {number}
 */
export function getUsernameType(username) {
  if (isUsername(username)) {
    return 1
  } else if (isPhoneNumber(username)) {
    return 2
  }
}

export function copyProps(source, target) {
  const temp = Object.assign({}, target)
  for (const key in target) {
    if (Object.prototype.hasOwnProperty.call(target, key) && source[key] !== undefined && source[key] !== null) {
      temp[key] = source[key]
    }
  }
  return temp
}

export function convertForm(source) {
  const tempObj = Object.assign({}, source)
  if (tempObj.dateRange) {
    tempObj.startDate = tempObj.dateRange[0]
    tempObj.endDate = tempObj.dateRange[1]
  }
  return tempObj
}

/**
 * 检查阿里云OSS STS令牌是否过期
 * @param sts
 * @returns {boolean} true：已过期 false：未过期
 */
export function isExpirationForAliyunOssSts(sts) {
  return !sts || (Date.parse(sts.expiration) - Date.now()) < 60000
}

export function getChangedField(backup, changed) {
  const temp = {}
  for (const key in changed) {
    if (Object.prototype.hasOwnProperty.call(changed, key)) {
      if (changed[key] !== backup[key]) {
        temp[key] = changed[key]
      }
    }
  }
  return temp
}

/**
 * 公钥加密
 * @param string
 * @returns {PromiseLike<ArrayBuffer>}
 */
export function encryptByPub(string) {
  const encrypt = new JSEncrypt()
  encrypt.setPublicKey('-----BEGIN PUBLIC KEY-----\n' +
    'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxsk4ZNm6yUBkM8sHgqF/\n' +
    'UH4xacAeejrAbgAz0OujbDp0PnYaLDtLU6891SteOk0UcaAoNSDssXHqXW/7HxL6\n' +
    'OrDVyeBqy7V7Z0jJzsiK9AKmrQ5NDIXpJFOVAJHYKyGJOgd8grkYFyG1r3+AmtDe\n' +
    'W7t+qAu6YRQEQkmm5fwezXesdNKMLNTnpULfonIGRqJpMlkqnxoklwzW5J6ASwtU\n' +
    'YEhUZ0qU2L98lW6rG9MOUAhD/WTdMapZG1OWY0Cf5yVL2ooSE+UScGvNtj//ID8d\n' +
    '4pUyChw7bOuo1oQ1Bdo6yORoEjPknHxnb239JCGJ5ra/ZpRObT4wsiqiAS/d6P0d\n' +
    'WwIDAQAB\n' +
    '-----END PUBLIC KEY-----\n')
  return encrypt.encrypt(string)
}

export function convertRes2Blob(response) {
  // 提取文件名
  const filename = response.headers['content-disposition'].match(
    /filename=(.*)/
  )[1]
  // 将二进制流转为blob
  const blob = new Blob([response.data], { type: 'application/octet-stream' })
  if (typeof window.navigator.msSaveBlob !== 'undefined') {
    // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
    window.navigator.msSaveBlob(blob, decodeURI(filename))
  } else {
    // 创建新的URL并指向File对象或者Blob对象的地址
    const blobURL = window.URL.createObjectURL(blob)
    // 创建a标签，用于跳转至下载链接
    const tempLink = document.createElement('a')
    tempLink.style.display = 'none'
    tempLink.href = blobURL
    tempLink.setAttribute('download', decodeURI(filename))
    // 兼容：某些浏览器不支持HTML5的download属性
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank')
    }
    // 挂载a标签
    document.body.appendChild(tempLink)
    tempLink.click()
    document.body.removeChild(tempLink)
    // 释放blob URL地址
    window.URL.revokeObjectURL(blobURL)
  }
}

export function downloadFile(href) {
  // const blobURL = window.URL.createObjectURL(blob)
  // 创建a标签，用于跳转至下载链接
  const tempLink = document.createElement('a')
  tempLink.style.display = 'none'
  tempLink.href = href
  tempLink.setAttribute('target', '_blank')
  // tempLink.setAttribute('download', decodeURI(filename))
  // 兼容：某些浏览器不支持HTML5的download属性
  // if (typeof tempLink.download === 'undefined') {
  // }
  // 挂载a标签
  document.body.appendChild(tempLink)
  tempLink.click()
  document.body.removeChild(tempLink)
}

/**
 * 是否是电脑微信浏览器
 * @returns {boolean}
 */
export function isWindowsWechat() {
  return navigator.userAgent.indexOf('WindowsWechat') !== -1
}

export function thisWeek() {
  const format = 'YYYY-MM-DD'
  const now = dayjs()
  const firstDay = now.subtract(7, 'day')
  const lastDay = now.subtract(1, 'day')
  return [firstDay.format(format), lastDay.format(format)]
}
